import { onMounted, ref } from 'vue'
import { getViewStatementApi } from '@/api/view'

export function useInfo<T>(viewId: string, init: () => void) {
  const infoData = ref<T>({} as T)
  const statement = ref<any>()
  const infoLoading = ref<boolean>(false)
  const isNew = ref<boolean>(true)

  onMounted(() => {
    getViewStatementApi(viewId).then((res: any) => {
      statement.value = res.data
      init()
    })
  })

  function hiddenItem(item: string) {
    action(item, it => it.visible = false)
  }

  function showItem(item: string) {
    action(item, it => it.visible = true)
  }

  function errorItem(item: string, msg: string) {
    action(item, it => it.error = msg)
  }

  function validErrors(errors: any) {
    const groups = statement.value.groups
    groups.forEach((group: any) => {
      group.data.forEach((item: any) => {
        item.forEach((it: any) => it.error = null)
      })
    })
    for (const key in errors) {
      errorItem(key, errors[key])
    }
  }

  function action(property: string, cb: (item: any) => void) {
    const groups = statement.value.groups
    groups.forEach((group: any) => {
      group.data.forEach((item: any) => {
        const find = item.find((it: any) => it.property === property)
        if (find !== undefined) {
          cb(find)
        }
      })
    })
  }

  return { statement, infoLoading, infoData, isNew, hiddenItem, showItem, errorItem, validErrors }
}
